﻿using lib;
using System;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Windows.Forms;

namespace DocClient
{
    public partial class DoctorForm : Form
    {
        public TcpClient serverConnection;
        internal readonly BinaryFormatter BinaryFormatter = new BinaryFormatter();
        internal int selectedclient = 0;
        public SecureConnectionClient secureConnection { get; set; }
        public SelectFileForm sf;
        internal int age { get; set; }
        internal int gender { get; set; }
        internal int gewicht { get; set; }
        internal int hearthbeat { get; set; }
        internal int rpm { get; set; }

        public DoctorForm(TcpClient docConnection, SecureConnectionClient sc)
        {
            InitializeComponent();
            serverConnection = docConnection;
            secureConnection = sc;
            SetStatusLabel("Succesfully connected to the server!");
            Thread oThread = new Thread(new DocThread().Handle);
            oThread.Start((object)this);
        }

        delegate void SetTextCallback(string text);

        internal void SetTime(string timestamp)
        {
            string[] iets = timestamp.Split(':');
            foreach (ClientTile naam in clientPanel.Controls)
                if (naam.Clientnr == Convert.ToInt32(iets[2]))
                {
                    if (naam.timeLabel.InvokeRequired)
                        Invoke(new SetTextCallback(SetTime), new object[] {timestamp});
                    else
                        naam.timeLabel.Text = iets[0]+":"+iets[1];
                    break;
                }
        }

        internal void SetRNaam(String naam)
        {
            if (nameLabel.InvokeRequired)
                Invoke(new SetTextCallback(SetRNaam), new object[] { naam });
            else
                nameLabel.Text = naam;
        }

        internal void SetRHeartBeat(String naam)
        {
            if (heartRateLabel.InvokeRequired)
                Invoke(new SetTextCallback(SetRHeartBeat), new object[] { naam });
            else
                heartRateLabel.Text = naam;
        }

        internal void SetRSpeed(String naam)
        {
            if (speedLabel.InvokeRequired)
                Invoke(new SetTextCallback(SetRSpeed), new object[] { naam });
            else
                speedLabel.Text = naam;
        }

        internal void SetRPower(String naam)
        {
            if (powerLabel.InvokeRequired)
                Invoke(new SetTextCallback(SetRPower), new object[] { naam });
            else
                powerLabel.Text = naam;
        }

        internal void SetRTime(String naam)
        {
            if (timeLabel.InvokeRequired)
                Invoke(new SetTextCallback(SetRTime), new object[] { naam });
            else
                timeLabel.Text = naam;
        }

        internal void SetRrpm(String naam)
        {
            if (rpmLabel.InvokeRequired)
                Invoke(new SetTextCallback(SetRrpm), new object[] { naam });
            else
                rpmLabel.Text = naam;
        }

        internal void SetRDesiredPower(String naam)
        {
            if (desiredPowerLabel.InvokeRequired)
                Invoke(new SetTextCallback(SetRDesiredPower), new object[] { naam });
            else
                desiredPowerLabel.Text = naam;
        }

        internal void SetREnergy(String naam)
        {
            if (energyLabel.InvokeRequired)
                Invoke(new SetTextCallback(SetREnergy), new object[] { naam });
            else
                energyLabel.Text = naam;
        }

        internal void SetDistance(String naam)
        {
            if (distanceLabel.InvokeRequired)
                Invoke(new SetTextCallback(SetDistance), new object[] { naam });
            else
            {
                distanceLabel.Text = naam;               
            }
        }
        

        public void InitPatient(String patientnaam)
        {
            if (clientPanel.InvokeRequired)
                Invoke(new SetTextCallback(InitPatient), new object[] {patientnaam});
            else
            {
                String[] sub = patientnaam.Split(':');
                clientPanel.Controls.Add(new ClientTile(sub[0], sub[1],this));
            }
        }

        public void SetPatientnaam(String patientnaam)
        {
            foreach (ClientTile clientTile in clientPanel.Controls)
                if (clientTile.User == patientnaam)
                {
                    if (clientTile.nameLabel.InvokeRequired)
                        Invoke(new SetTextCallback(SetPatientnaam), new object[] {patientnaam});
                    else
                        clientTile.nameLabel.Text = patientnaam;
                    break;
                }
        }

        internal void SetpatientHearthbeat(string patientHeartBeat)
        {
            string[] iets = patientHeartBeat.Split(':');
            foreach (ClientTile naam in clientPanel.Controls)
                if (naam.Clientnr == Convert.ToInt32(iets[1]))
                {
                    if (naam.heartRateLabel.InvokeRequired)
                        Invoke(new SetTextCallback(SetpatientHearthbeat), new object[] {patientHeartBeat});
                    else
                        naam.heartRateLabel.Text = iets[0];
                    hearthbeat = Convert.ToInt32(iets[0]);
                    break;
                }
        }

        internal void RemovePatient(String patientnummer)
        {
            Convert.ToInt32(patientnummer);
            ClientTile tile = null;
            foreach (ClientTile naam in clientPanel.Controls)
                if (naam.Clientnr == Convert.ToInt32(patientnummer))
                {
                    if (naam.InvokeRequired)
                        Invoke(new SetTextCallback(RemovePatient), new object[] {patientnummer});
                    else
                        tile = naam;
                    break;
                }
            clientPanel.Controls.Remove(tile);
        }

        public void SetpatientPower(String patientpower)
        {
            string[] iets = patientpower.Split(':');
            foreach (ClientTile naam in clientPanel.Controls)
                if (naam.Clientnr == Convert.ToInt32(iets[1]))
                {
                    if (naam.powerLabel.InvokeRequired)
                        Invoke(new SetTextCallback(SetpatientPower), new object[] {patientpower});
                    else
                        naam.powerLabel.Text = iets[0];
                    break;
                }
        }

        public void OutputTextBoxMessage(String message)
        {
            string[] iets = message.Split(':');
            foreach (ClientTile naam in clientPanel.Controls)
            {
                if (naam.nameLabel.Text == iets[0])
                {
                    if (naam.pictureBox1.InvokeRequired)
                    {
                        SetTextCallback d = new SetTextCallback(OutputTextBoxMessage);
                        Invoke(d, new object[] {message});
                    }
                    else
                    {
                        naam.ChatMess += message + System.Environment.NewLine;
                        if(selectedclient == naam.Clientnr)
                            SetOutputTextBoxMessage(naam.ChatMess);
                        else
                            naam.pictureBox1.Visible = true;
                    }
                }
            }
        }

        public void SetStatusLabel(String message)
        {
                statusLabel.Text = message;
        }

        private void DoctorForm_Load(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void inputTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((int)e.KeyChar == 13)
            {
                if (clientPanel.Controls.Count > 0 && inputTextBox.Text != "")
                {
                    //BinaryFormatter.Serialize(serverConnection.GetStream(), "chat: " + inputTextBox.Text + ":" + selectedclient);
                    inputTextBox.Text = inputTextBox.Text.Replace(':', ' ');
                    secureConnection.SendObject("chat: " + inputTextBox.Text + ":" + selectedclient);
                    outputTextBox.Text += "Doctor: " + inputTextBox.Text + System.Environment.NewLine;
                    foreach (ClientTile clientTile in clientPanel.Controls)
                        if (clientTile.Clientnr == selectedclient)
                            clientTile.ChatMess += "Doctor: " + inputTextBox.Text + System.Environment.NewLine;
                    inputTextBox.Text = "";
                }
                else
                {
                    outputTextBox.Text += "Select a client and make sure your message isn't empty." + System.Environment.NewLine;
                }
            }
        }

        private void inputTextBox_TextChanged(object sender, EventArgs e)
        {

        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (clientPanel.Controls.Count > 0 || !(inputTextBox.Text.Trim() != ""))
            {
                //BinaryFormatter.Serialize(serverConnection.GetStream(), "chat: " + inputTextBox.Text + ":all");
                inputTextBox.Text = inputTextBox.Text.Replace(':', ' ');
                secureConnection.SendObject("chat: " + inputTextBox.Text + ":all");
                outputTextBox.Text += "Doctor to all: " + inputTextBox.Text + System.Environment.NewLine;
                foreach (ClientTile clientTile in clientPanel.Controls)
                        clientTile.ChatMess += "Doctor to all: " + inputTextBox.Text + System.Environment.NewLine;
                inputTextBox.Text = "";
            }
            else
            {
                outputTextBox.Text += "Make sure there are clients connected to the server and your message isn't empty.";
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //secureConnection.ClosesslStream();
            //this.Close();
            Application.Exit();
            //verschil met Close?
        }

        private void aboutToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            MessageBox.Show("Best Team Ever 23JTI2A3", "About", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }

        private void viewHelpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Here we will show some help information, READ THE README", "Help", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //secureConnection.ClosesslStream();
            //this.Close();
            Application.Exit();
            //verschil met Exit ?
        }

        internal void SetOutputTextBoxMessage(string ChatMess)
        {
            if (outputTextBox.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetOutputTextBoxMessage);
                Invoke(d, new object[] { ChatMess });
            }
            else
            {
                outputTextBox.Text = ChatMess;
            }
        }
        private void GetLogs_Click(object sender, EventArgs e)
        {
            sf = new SelectFileForm(this);
            sf.Show();
            sf.AcquireLogs();
        }
    
        private void powerTrackBar_ValueChanged(object sender, EventArgs e)
        {
            if (powerTrackBar.Value % 5 != 0)
            {
                powerTrackBar.Value -= powerTrackBar.Value % 5;
            }
            setPowerLabel.Text = powerTrackBar.Value + "";
            secureConnection.SendObject("BikeCommand:"+selectedclient+":PW:" + powerTrackBar.Value);
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            Thread trainingThread = new Thread(new ThreadStart(createThread));
            trainingThread.Start();
        }

        private void createThread()
        {
            new Training(gender, age, gewicht, selectedclient, this);
        }
    }
}
